Component({
  properties: {
    // 允许页面传入当前选中的索引（0: 首页，1: 扫一扫，2: 个人中心）
    active: {
      type: Number,
      value: 0,
      observer(val) {
        const n = Number(val);
        if (!isNaN(n)) this.setData({ selected: n });
      }
    }
  },

  data: {
    selected: 0,
    tabBarHeight: 0,
    isDark: false,
    list: [
      {
        pagePath: '/pages/index/index',
        text: '首页',
        iconPath: '/images/home.png',
        selectedIconPath: '/images/home_active.png'
      },
      {
        pagePath: '/pages/scan/scan',
        text: '扫一扫',
        iconPath: '/images/scan.png',
        selectedIconPath: '/images/scan_active.png'
      },
      {
        pagePath: '/pages/profile/profile',
        text: '个人中心',
        iconPath: '/images/profile.png',
        selectedIconPath: '/images/profile_active.png',
        dot: false // 小红点
      }
    ]
  },

  lifetimes: {
    attached() {
      const sys = wx.getSystemInfoSync();
      const rpx2px = sys.windowWidth / 750;
      // 与首页自定义 tabbar 统一：160rpx 的容器高度（用于给凸起按钮留空间）
      this.setData({ tabBarHeight: 160 * rpx2px });

      // 监听主题
      this.updateDarkMode(sys.theme);
      wx.onThemeChange?.(res => this.updateDarkMode(res.theme));

      // 首次根据 active 设置选中项
      const n = Number(this.properties.active);
      if (!isNaN(n)) this.setData({ selected: n });
    }
  },

  methods: {
    updateDarkMode(theme) {
      this.setData({ isDark: theme === 'dark' });
    },

    switchTab(e) {
      const { path, index } = e.currentTarget.dataset;
      if (!path) return;
      wx.switchTab({ url: path });
      this.setData({ selected: Number(index) });
    },

    // 中间凸起按钮点击（跳转到“扫一扫”页）
    goCenter() {
      const path = this.data.list[1]?.pagePath;
      if (path) {
        wx.switchTab({ url: path });
        this.setData({ selected: 1 });
      }
    },

    /* 对外暴露的接口 */
    setBadge(index, num) {
      const key = `list[${index}].badge`;
      this.setData({ [key]: num });
    },
    setDot(index, show) {
      const key = `list[${index}].dot`;
      this.setData({ [key]: show });
    }
  }
});